//
//  SISSCalculateViewController.m
//  SISSAPP
//
//  Created by 优房网 on 2017/5/3.
//  Copyright © 2017年 优房网. All rights reserved.
//

#import "SISSCalculateViewController.h"
#import "SISSCalculateFillInCell.h"
#import "SISSCalculateChooseCell.h"
#import "SISSCalculateCell.h"
#import "SISSPickerView.h"
#import "SISSCalculateModel.h"
#import "SISSCalculateResultViewController.h"
#import "SISSCalculateDeliveryModel.h"

static NSString *calculateChooseCellID = @"calculateChooseCellID";
static NSString *calculateCellID = @"calculateCellID";


@interface SISSCalculateViewController ()<UITableViewDelegate,UITableViewDataSource,SISSCalculateCellDelegate>
@property (weak, nonatomic) IBOutlet SISSBaseTableView *tableView;

/* 是否是贷款总额 */
@property (assign, nonatomic) BOOL isLoanTotal;

@property (assign, nonatomic) SISSCalculateType calculateType;

/* cell行数 */
@property (assign, nonatomic) NSInteger section;

/* 贷款总额 */
@property (strong, nonatomic) NSArray<SISSCalculateModel *> *chooseLoanTotalArr;
/* 房价总额 */
@property (strong, nonatomic) NSArray<SISSCalculateModel *> *choosePriceTotalArr;

/* 公积金利率数组 */
@property (strong, nonatomic) NSArray *reservedRateArr;
/* 商贷利率 */
@property (strong, nonatomic) NSArray *commercialRateArr;
/* 贷款比例 */
@property (strong, nonatomic) NSArray *loanRatioArr;
/* 贷款年限 */
@property (strong, nonatomic) NSArray *loanYearArr;

/* 计算方式 */
@property (assign, nonatomic) NSInteger calculateIndex;
/* 贷款年限 */
@property (assign, nonatomic) NSInteger loanYearIndex;
/* 公积金利率 */
@property (assign, nonatomic) NSInteger reservedLoanRateIndex;
/* 商贷利率 */
@property (assign, nonatomic) NSInteger commercialLoanRateIndex;
/* 贷款比例 */
@property (assign, nonatomic) NSInteger loanRatioIndex;

/* 房价总额 */
@property (copy, nonatomic) NSString *houseTotalMoney;
/* 贷款总额 */
@property (copy, nonatomic) NSString *totalLoanMoney;
/* 公积金贷款 */
@property (copy, nonatomic) NSString *reservedLoanMoney;
/* 商业贷款 */
@property (copy, nonatomic) NSString *commercialLoanMoney;

/* 公积金贷款基准利率 */
@property (assign, nonatomic) CGFloat reservedBaseRate;
/* 商业贷款基准利率 */
@property (assign, nonatomic) CGFloat commercialBaseRate;

/**
 标记是否是第一次输入公积金金额
 */
@property (assign, nonatomic) BOOL isFirstFillIn;
@property (assign, nonatomic) BOOL isReserved;

@property (assign, nonatomic) BOOL isFirstCellFillIn;

@end

@implementation SISSCalculateViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.isFirstFillIn = NO;
    self.isFirstCellFillIn = NO;
    self.reservedBaseRate = 3.25;
    self.commercialBaseRate = 4.9;
    
    self.section = 5;
    self.calculateIndex = 1;
    self.loanYearIndex = 29;
    self.reservedLoanRateIndex = 0;
    self.commercialLoanRateIndex = 0;
    self.loanRatioIndex = 10;
    self.calculateType = SISSCalculateTypeReserved;
    self.isLoanTotal = YES;
}

- (void)setupSubviews {
    
    self.chooseLoanTotalArr = [SISSCalculateModel loadReservedFunds1Data];
    self.choosePriceTotalArr = [SISSCalculateModel loadReservedFunds2Data];
    
    [super setupSubviews];
    
    // tableView相关
    
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"SISSCalculateChooseCell" bundle:nil] forCellReuseIdentifier:calculateChooseCellID];
    [self.tableView registerNib:[UINib nibWithNibName:@"SISSCalculateFillInCell" bundle:nil] forCellReuseIdentifier:@"SISSCalculateFillInCellReuseID"];
    [self.tableView registerNib:[UINib nibWithNibName:@"SISSCalculateCell" bundle:nil] forCellReuseIdentifier:calculateCellID];
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.section = self.isLoanTotal ? self.chooseLoanTotalArr.count + 1 : self.choosePriceTotalArr.count + 1;
    return self.section;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == self.section - 1) {
        SISSCalculateCell *calculateCell = [tableView dequeueReusableCellWithIdentifier:calculateCellID forIndexPath:indexPath];
        calculateCell.delegate = self;
        return calculateCell;
    } else  {
        
        SISSCalculateModel *model = self.isLoanTotal ? self.chooseLoanTotalArr[indexPath.row] : self.choosePriceTotalArr[indexPath.row];
        
        __block BOOL isReserved = YES;
        
        if (model.flag){
            SISSCalculateChooseCell *chooseCell = [tableView dequeueReusableCellWithIdentifier:calculateChooseCellID forIndexPath:indexPath];
            chooseCell.leftLabel.text = model.left;
            chooseCell.rightLabel.text = model.right;
            return chooseCell;
        } else {
            SISSCalculateFillInCell *fillInCell = [tableView dequeueReusableCellWithIdentifier:@"SISSCalculateFillInCellReuseID" forIndexPath:indexPath];
            fillInCell.leftLabel.text = model.left;
            fillInCell.rightTextField.placeholder = model.right;
//            fillInCell.rightTextField.text = @"";
            if (indexPath.row == 1 && self.isLoanTotal && self.isFirstCellFillIn) {
                
                fillInCell.rightTextField.text = self.totalLoanMoney.length > 0 ? self.totalLoanMoney : @"";
                fillInCell.isReserved = self.calculateType == SISSCalculateTypeReserved ? YES : NO;
            }
            
            // 组合贷款按房贷总额 设置公积金和商贷的自动填充
            if (!self.isLoanTotal && (indexPath.row == 3 || indexPath.row == 4 || indexPath.row == 6) && self.houseTotalMoney.length ) {
                
                NSInteger count = [self.houseTotalMoney integerValue] * [self.loanRatioArr[self.loanRatioIndex] integerValue] * 0.01;
                
                NSString *totalM = [NSString stringWithFormat:@"%zd",count];
                fillInCell.isRatio = YES;
                fillInCell.checkNum = [totalM integerValue];
                if (indexPath.row == 3) {
                    fillInCell.rightTextField.text = totalM;
                }
                self.totalLoanMoney = totalM;
                
                if (indexPath.row == 4 && self.isFirstFillIn) {
                    fillInCell.isReserved = YES;
                    fillInCell.rightTextField.text = self.isReserved ? self.reservedLoanMoney : [NSString stringWithFormat:@"%zd",count - [self.commercialLoanMoney integerValue]];
                    
                    self.reservedLoanMoney = fillInCell.rightTextField.text;
                }
                if (indexPath.row == 6 && self.isFirstFillIn) {
                    fillInCell.rightTextField.text = self.isReserved ? [NSString stringWithFormat:@"%zd",count - [self.reservedLoanMoney integerValue]] : self.commercialLoanMoney;
                    self.commercialLoanMoney = fillInCell.rightTextField.text;
                }
            }
            
            // 组合贷款按贷款总额 设置公积金和商贷的自动填充
            if (self.calculateType == SISSCalculateTypeComBined && self.isLoanTotal && (indexPath.row == 2 || indexPath.row == 4) && self.isFirstFillIn) {
                
                fillInCell.isRatio = YES;
                fillInCell.checkNum = [self.totalLoanMoney integerValue];
                if (indexPath.row == 2) {
                    fillInCell.isReserved = YES;
                    fillInCell.rightTextField.text = self.isReserved ? self.reservedLoanMoney : [NSString stringWithFormat:@"%zd",[self.totalLoanMoney integerValue] - [self.commercialLoanMoney integerValue]];
                    self.reservedLoanMoney = fillInCell.rightTextField.text;
                }
                if (indexPath.row == 4) {
                    fillInCell.rightTextField.text = self.isReserved ? [NSString stringWithFormat:@"%zd",[self.totalLoanMoney integerValue] - [self.reservedLoanMoney integerValue]] : self.commercialLoanMoney;
                    self.commercialLoanMoney = fillInCell.rightTextField.text;
                }
            }
            
            // 填写回调
            fillInCell.textFieldChangeBlock = ^(NSString *text) {
                if (self.isLoanTotal) {
                    switch (indexPath.row) {
                        case 1: {
                            self.totalLoanMoney = text;
                            self.isFirstCellFillIn = YES;
                        }
                            break;
                            
                        case 2: {
                            self.isFirstFillIn = YES;
                            self.reservedLoanMoney = text;
                            isReserved = YES;
                        }
                            break;
                            
                        case 4: {
                            self.isFirstFillIn = YES;
                            self.commercialLoanMoney = text;
                            isReserved = NO;
                        }
                            break;
                            
                        default:
                            break;
                    }
                } else {
                    switch (indexPath.row) {
                        case 1: {
                            self.houseTotalMoney = text;
                        }
                            break;
                            
                        case 3: {
                            self.totalLoanMoney = text;
                        }
                            break;
                            
                        case 4: {
                            self.isFirstFillIn = YES;
                            self.reservedLoanMoney = text;
                            isReserved = YES;
                        }
                            break;
                            
                        case 6: {
                            self.isFirstFillIn = YES;
                            self.commercialLoanMoney = text;
                            isReserved = NO;
                        }
                            break;
                            
                        default:
                            break;
                    }
                }
                self.isReserved = isReserved;
                [self.tableView reloadData];
                NSLog(@"text %@", text);
            };
            fillInCell.isReserved = model.isAccumulationFund;
            return fillInCell;
        }
    }
}

#pragma mark - SISSCalculateCellDelegate
- (void)calculateButtondidClicked {
    
    [self.view endEditing:YES];
    if ([self.totalLoanMoney floatValue] <= 0) {
        [self alertActionAlertWithTitle:@"提示" message:@"请输入贷款总额"];
        return;
    }
    if ([self.reservedLoanMoney floatValue] > 120 || (self.calculateType == SISSCalculateTypeReserved && [self.totalLoanMoney floatValue] > 120)) {
        [self alertActionAlertWithTitle:@"提示" message:@"目前公积金最大贷款上限为120万"];
        return;
    }
    if (self.calculateType == SISSCalculateTypeComBined && [self.reservedLoanMoney floatValue] <= 0 && [self.commercialLoanMoney floatValue] <= 0) {
        [self alertActionAlertWithTitle:@"提示" message:@"请输入公积金或商业贷款金额"];
        return;
    }
    
    SISSCalculateResultViewController *vc = [[SISSCalculateResultViewController alloc] init];
    
    SISSCalculateDeliveryModel *model = [[SISSCalculateDeliveryModel alloc] init];
    
    model.calculateType = self.calculateType;
    model.totalLoanMoney = [self.totalLoanMoney floatValue];
    model.houseTotalMoney = [self.houseTotalMoney floatValue];
    model.reservedLoanMoney = [self.reservedLoanMoney floatValue];
    model.commercialLoanMoney = [self.commercialLoanMoney floatValue];
    model.reservedRate = [self.reservedRateArr[self.reservedLoanRateIndex] floatValue] * self.reservedBaseRate * 0.01;
    model.commercialRate = [self.commercialRateArr[self.commercialLoanRateIndex] floatValue] * self.commercialBaseRate *0.01;
    model.loanRatio = [self.loanRatioArr[self.loanRatioIndex] integerValue] * 0.01;
    model.loanYear = [self.loanYearArr[self.loanYearIndex] integerValue];
    
    vc.model = model;
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - 点击tableViewcell
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [self.tableView endEditing:YES];
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.row == self.section - 1) return; // 拦截最后一行cell的点击
    
    SISSCalculateModel *model = self.isLoanTotal ? self.chooseLoanTotalArr[indexPath.row] : self.choosePriceTotalArr[indexPath.row];
    
    if (model.flag) { // 判断点击的是否是选择类型cell
        
        NSInteger yearIndex = self.calculateType == SISSCalculateTypeComBined ? self.section - 2 : self.section - 3;
        SISSCalculateChooseCell *chooseCell = [tableView cellForRowAtIndexPath:indexPath];
        switch (indexPath.row) {
            case 0: {
                
                SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
                pickerView.title = @"计算方式";
                pickerView.titleArray = @[@"按房价总额", @"按贷款总额"];
                pickerView.isArea = NO;
                pickerView.firstIndex = self.calculateIndex;
                __weak typeof(self) weakself = self;
                pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
                    chooseCell.rightLabel.text = firstTitle;
                    weakself.calculateIndex = firstIndex;
                    weakself.isLoanTotal = firstIndex;
                    [weakself.tableView reloadData];
                };
            }
                break;
                
            case 2: {
                if (!self.isLoanTotal) {
                    
                    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
                    pickerView.title = @"贷款比例";
                    NSMutableArray *titleArr = [NSMutableArray arrayWithCapacity:13];
                    for (NSInteger i = 20; i <= 80; i+=5) {
                        [titleArr addObject:[NSString stringWithFormat:@"%zd%@",i,@"%"]];
                    }
                    pickerView.titleArray = titleArr;
                    pickerView.isArea = NO;
                    pickerView.firstIndex = self.loanRatioIndex;
                    __weak typeof(self) weakself = self;
                    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
                        chooseCell.rightLabel.text = firstTitle;
                        weakself.loanRatioIndex = firstIndex;
                        if (weakself.isLoanTotal) {
                            weakself.chooseLoanTotalArr[indexPath.row].right = firstTitle;
                        } else {
                            weakself.choosePriceTotalArr[indexPath.row].right = firstTitle;
                        }
                        [weakself.tableView reloadData];
                    };
                } else {
                    
                    if (indexPath.row == yearIndex) {
                        
                        SISSCalculateChooseCell *chooseCell = [tableView cellForRowAtIndexPath:indexPath];
                        
                        SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
                        pickerView.title = @"贷款年限";
                        NSMutableArray *titleArr = [NSMutableArray arrayWithCapacity:30];
                        for (NSInteger i = 0; i < 30; i++) {
                            [titleArr addObject:[NSString stringWithFormat:@"%zd年",i + 1]];
                        }
                        pickerView.titleArray = titleArr;
                        pickerView.isArea = NO;
                        pickerView.firstIndex = self.loanYearIndex;
                        __weak typeof(self) weakself = self;
                        pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
                            chooseCell.rightLabel.text = firstTitle;
                            weakself.loanYearIndex = firstIndex;
                            if (self.isLoanTotal) {
                                self.chooseLoanTotalArr[indexPath.row].right = firstTitle;
                            } else {
                                self.choosePriceTotalArr[indexPath.row].right = firstTitle;
                            }
                        };
                    }
                }
            }
                break;
                
            case 3:
            case 5:
            case 7: {
                
                SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
                
                NSArray *commercialArr = @[@"最新基准利率", @"最新基准利率9.5折", @"最新基准利率9折", @"最新基准利率8.8折", @"最新基准利率8.7折", @"最新基准利率8.6折", @"最新基准利率8.5折", @"最新基准利率8.2折", @"最新基准利率8折", @"最新基准利率7.5折", @"最新基准利率7折", @"最新基准利率1.1倍", @"最新基准利率1.2倍", @"最新基准利率1.3倍"];
                NSArray *reservedArr = @[@"最新基准利率", @"最新基准利率1.1倍", @"最新基准利率1.2倍"];
                
                NSString *title;
                NSArray *titleArr;
                NSArray *rateArr;
                CGFloat rate;
                
                switch (self.calculateType) {
                    case SISSCalculateTypeReserved: {
                        title = @"贷款利率";
                        titleArr = reservedArr;
                        rate = self.reservedBaseRate;
                        rateArr = self.reservedRateArr;
                    }
                        break;
                        
                    case SISSCalculateTypeCommercial: {
                        title = @"商贷利率";
                        titleArr = commercialArr;
                        rate = self.commercialBaseRate;
                        rateArr = self.commercialRateArr;
                    }
                        break;
                        
                    case SISSCalculateTypeComBined: {
                        
                        if (self.isLoanTotal) {
                            title = indexPath.row == 3 ? @"公积金利率" : @"商贷利率";
                            titleArr = indexPath.row == 3 ? reservedArr : commercialArr;
                            rate = indexPath.row == 3 ? self.reservedBaseRate : self.commercialBaseRate;
                            rateArr = indexPath.row == 3 ? self.reservedRateArr : self.commercialRateArr;
                        } else {
                            title = indexPath.row == 5 ? @"公积金利率" : @"商贷利率";
                            titleArr = indexPath.row == 5 ? reservedArr : commercialArr;
                            rate = indexPath.row == 5 ? self.reservedBaseRate : self.commercialBaseRate;
                            rateArr = indexPath.row == 5 ? self.reservedRateArr : self.commercialRateArr;
                        }
                    }
                        break;
                        
                    default:
                        break;
                }
                pickerView.title = title;
                
                BOOL isCommercial = [title isEqualToString:@"商贷利率"];
                pickerView.titleArray = titleArr;
                pickerView.isArea = NO;
                pickerView.firstIndex = isCommercial ? self.commercialLoanRateIndex : self.reservedLoanRateIndex;
                __weak typeof(self) weakself = self;
                pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
                    
                    NSString *textStr = [NSString stringWithFormat:@"%@(%0.2f%@)",firstTitle,rate * [rateArr[firstIndex] floatValue],@"%"];
                    chooseCell.rightLabel.text = textStr;
                    if (isCommercial) {
                        weakself.commercialLoanRateIndex = firstIndex;
                    } else {
                        weakself.reservedLoanRateIndex = firstIndex;
                    }
                    if (self.isLoanTotal) {
                        self.chooseLoanTotalArr[indexPath.row].right = textStr;
                    } else {
                        self.choosePriceTotalArr[indexPath.row].right = textStr;
                    }
                };
            }
                break;
                
                // 贷款年限
            case 4:
            case 6:
            case 8: {
                
                if (indexPath.row == yearIndex) {
                    
                    SISSCalculateChooseCell *chooseCell = [tableView cellForRowAtIndexPath:indexPath];
                    
                    SISSPickerView *pickerView = [[SISSPickerView alloc] initWithFrame:self.view.bounds];
                    pickerView.title = @"贷款年限";
                    NSMutableArray *titleArr = [NSMutableArray arrayWithCapacity:30];
                    for (NSInteger i = 0; i < 30; i++) {
                        [titleArr addObject:[NSString stringWithFormat:@"%zd年",i + 1]];
                    }
                    pickerView.titleArray = titleArr;
                    pickerView.isArea = NO;
                    pickerView.firstIndex = self.loanYearIndex;
                    __weak typeof(self) weakself = self;
                    pickerView.completion = ^(NSString *firstTitle, NSString *secondTitle, NSInteger firstIndex, NSInteger secondIndex) {
                        chooseCell.rightLabel.text = firstTitle;
                        model.right = firstTitle;
                        weakself.loanYearIndex = firstIndex;
                        if (self.isLoanTotal) {
                            self.chooseLoanTotalArr[indexPath.row].right = firstTitle;
                        } else {
                            self.choosePriceTotalArr[indexPath.row].right = firstTitle;
                        }
                    };
                }
            }
                break;
                
            default:
                break;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return indexPath.row == self.section - 1 ? 108 : 44;
}



#pragma mark - 点击segmentControl的响应事件
- (IBAction)segmentControlClickAction:(UISegmentedControl *)sender {
    
    [self.view endEditing:YES];
    NSLog(@"selectedSegmentIndex:  %zd",sender.selectedSegmentIndex);
    switch (sender.selectedSegmentIndex) {
            
        case 0: {
            
            self.chooseLoanTotalArr = [SISSCalculateModel loadReservedFunds1Data];
            self.choosePriceTotalArr = [SISSCalculateModel loadReservedFunds2Data];
            self.calculateType = SISSCalculateTypeReserved;
        }
            break;
            
        case 1: {
            
            self.chooseLoanTotalArr = [SISSCalculateModel loadCommercialLoan1Data];
            self.choosePriceTotalArr = [SISSCalculateModel loadCommercialLoan2Data];
            self.calculateType = SISSCalculateTypeCommercial;;
        }
            break;
            
        case 2: {
            
            self.chooseLoanTotalArr = [SISSCalculateModel loadCombinedLoan1Data];
            self.choosePriceTotalArr = [SISSCalculateModel loadCombinedLoan2Data];
            self.calculateType = SISSCalculateTypeComBined;
        }
            break;
            
        default:
            break;
    }
    
    self.isFirstFillIn = NO;
    self.isFirstCellFillIn = NO;
//    self.calculateIndex = 1;
    self.loanYearIndex = 29;
    self.reservedLoanRateIndex = 0;
    self.commercialLoanRateIndex = 0;
    self.loanRatioIndex = 10;
    
//    self.totalLoanMoney = @"";
//    self.reservedLoanMoney = @"";
//    self.commercialLoanMoney = @"";
//    self.houseTotalMoney = @"";
    
    [self.tableView reloadData];
    
}

#pragma mark - 懒加载
- (NSArray *)reservedRateArr {
    if (!_reservedRateArr) {
        _reservedRateArr = @[@1, @1.1, @1.2];
    }
    return _reservedRateArr;
}

- (NSArray *)commercialRateArr {
    
    if (!_commercialRateArr) {
        _commercialRateArr = @[@1, @0.95, @0.9, @0.88, @0.87, @0.86, @0.85, @0.82, @0.8, @0.75, @0.7, @1.1, @1.2, @1.3];
    }
    return _commercialRateArr;
}

- (NSArray *)loanRatioArr {
    
    if (!_loanRatioArr) {
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:13];
        for (NSInteger i = 20; i <= 80; i+=5) {
            [arr addObject:@(i)];
        }
        _loanRatioArr = [NSArray arrayWithArray:arr];
    }
    return _loanRatioArr;
}

- (NSArray *)loanYearArr {
    if (!_loanYearArr) {
        
        NSMutableArray *arr = [NSMutableArray arrayWithCapacity:30];
        for (NSInteger i = 0; i < 30; i++) {
            [arr addObject:@(i+1)];
        }
        _loanYearArr = [NSArray arrayWithArray:arr];
    }
    
    return _loanYearArr;
}


@end
